package cn.zwx.common.exception.starter.advice;

import cn.zwx.base.entity.ResponseEntity;
import cn.zwx.base.enums.ResponseCodeEnum;
import cn.zwx.base.exception.BizWrapException;
import cn.zwx.base.utils.json.JsonUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Lazy;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MaxUploadSizeExceededException;

import java.util.HashMap;
import java.util.Map;

/**
 * @author zhangwenxue
 */
@ControllerAdvice
@Lazy(false)
public class ExceptionControllerAdvice {
    private static final Logger logger = LoggerFactory.getLogger(ExceptionControllerAdvice.class);

    @Value("${spring.application.name}")
    private String appid;

    @ResponseBody
    @ExceptionHandler(BizWrapException.class)
    public ResponseEntity<Map<String, String>> handleBizWrapException(BizWrapException ex) {
        logger.error("服务:{} 业务异常", appid);
        return ResponseEntity.fail(ex.getCode(),ex.getMsg());
    }
    @ResponseBody
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ResponseEntity<String> handleMethodArgumentNotValidException(MethodArgumentNotValidException ex) {
        Map<String, String> response = new HashMap<>();
        ex.getBindingResult().getAllErrors().forEach((error) -> {
            String fieldName = ((FieldError) error).getField();
            String message = error.getDefaultMessage();
            response.put(fieldName, message);
        });
        logger.error("服务:{} 请求参数异常", appid);
        return ResponseEntity.fail(ResponseCodeEnum.REQUEST_PARMA_ERROR.getCode(), JsonUtils.toJsonString(response));
    }
    @ResponseBody
    @ExceptionHandler(MaxUploadSizeExceededException.class)
    public ResponseEntity<String> handleMaxUploadSizeExceededException(MaxUploadSizeExceededException ex) {
        String msg = "文件上传过大，请确保文件大小不超过 " + ex.getMaxUploadSize() / (1024 * 1024) + " MB";
        logger.error("服务:{} ,{}", appid,msg);
        return ResponseEntity.fail(ResponseCodeEnum.FILE_UPLOAD_SIZE_LIMIT_ERROR.getCode(), msg);
    }
    @ResponseBody
    @ExceptionHandler(HttpMessageNotReadableException.class)
    public ResponseEntity<String> handleHttpMessageNotReadableException(HttpMessageNotReadableException ex) {
        logger.error("服务:{} ,JSON 参数解析异常", appid);
        return  ResponseEntity.fail(ResponseCodeEnum.PARAM_PARSE_ERROR.getCode(), ex.getMessage());
    }
    @ResponseBody
    @ExceptionHandler(IllegalArgumentException.class)
    public ResponseEntity<Map<String, String>> handleIllegalArgumentException(IllegalArgumentException ex) {
        logger.error("服务:{} ,请求参数非法", appid);
        return  ResponseEntity.fail(ResponseCodeEnum.REQUEST_PARMA_ERROR.getCode(), ex.getMessage());

    }
    @ExceptionHandler({Exception.class})
    @ResponseBody
    public ResponseEntity<String> handleException(Exception ex) {
        logger.error("服务:{} ,未知异常", appid,ex);
        return ResponseEntity.fail(ResponseCodeEnum.UNKNOWN_ERROR.getCode(), ResponseCodeEnum.UNKNOWN_ERROR.getMsg());
    }
}
